/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.actionPage;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.ContentFieldValue;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.MenuItem;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.model.core.Sequence;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ActionPageForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.LinkedObjectsInfoContainer;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.ModuleUtils;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * <p>Updates action page
 * </p>
 * <p><a href="UpdateActionPageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.46 $ $Date: 2008/04/29 17:48:05 $
 * @struts.action name="actionPageForm"
 * path="/core/actionPage/update"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-actionPage-updateContent, core-actionPage-update"
 * @struts.action-forward name="inputForward"
 * path=".core.actionPage.update"
 * @struts.action-forward name="viewActionPage"
 * path="/core/actionPage/view.do"
 * redirect="true"
 * @struts.action-forward name="listActionPages"
 * path="/core/actionPage/list.do"
 * redirect="true"
 * @struts.action-forward name="callUpdateActionPage"
 * path="/core/actionPage/callUpdate.do"
 * redirect="false"
 * @struts.action-forward name="viewLinkedObjects"
 * path="/core/linkedObjects/view.do"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/actionPage/list.do"
 */
public final class UpdateActionPageAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		if ( !isCancelled(request) ) {
            // flag shows whether to force changing of URI if there're some
            // linked objects
            boolean force = "true".equalsIgnoreCase(request.getParameter("force"));

			ActionPageForm actionPageForm;
            if (force) {
                actionPageForm = (ActionPageForm) request.getSession().getAttribute(WebappConstants.ACTION_PAGE_FORM_KEY);
            } else {
                actionPageForm = (ActionPageForm) form;
            }

			if ( !WebappUtil.hasCorrectValues(actionPageForm.getTitleMap()) ) {
				// title must be specified
				ActionMessages errors = new ActionMessages();
				errors.add("title", new ActionMessage("core.commons.errors.required", getMessage(request, "core.page.form.title")));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			} 				

			// check URI for existence
			String uri = actionPageForm.getUri();
			ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig(request, getServlet().getServletContext());
			String prefix = moduleConfig.getPrefix();
			if ( log.isDebugEnabled() ) {
				log.debug("Prefix: " + prefix);
			}

			String actionPath = prefix + uri;

			if ( log.isDebugEnabled() ) {
				log.debug("Searching for action with path=" + actionPath);
			}

			if ( moduleConfig.findActionConfig(actionPath) == null ) {
				// action with this uri does not exist
				if ( log.isDebugEnabled() ) {
					log.debug("Action with uri '" + actionPath + "' does not exist");
				}
				ActionMessages errors = new ActionMessages();
				errors.add("actionPageIncorrectUri", new ActionMessage("core.actionPage.errors.incorrectUri"));
				saveErrors(request, errors, false);
				saveToken(request);
				return mapping.getInputForward();
			}

			Long actionPageId;
			if ( !GenericValidator.isBlankOrNull(actionPageForm.getId()) ) {
				actionPageId = Long.valueOf(actionPageForm.getId());
			} else {
				if ( log.isWarnEnabled() ) {
					log.warn("Missing action page ID. Returning to list...");
				}
				return mapping.findForward("listActionPages");
			}

			request.getSession().setAttribute(WebappConstants.ACTION_PAGE_ID_KEY, actionPageId);

			PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
			ActionPage actionPage = pageManager.retrieveActionPage(actionPageId);

			if ( actionPage == null ) {
				// action page not found. it might be deleted by someone else
				ActionMessages errors = new ActionMessages();
				errors.add("actionPageNotFound", new ActionMessage("core.actionPage.errors.notFound"));
				saveErrors(request, errors);
				return mapping.findForward("listActionPages");
			}

			String oldUri = actionPage.getUri();

            // Check whether user tries to change fields that he cannot change
            boolean canUpdateUriAndLinkable = request.isUserInRole("core-actionPage-update");
            if (!canUpdateUriAndLinkable && (!oldUri.equals(uri) || !actionPageForm.getActive().equals(actionPage.getActive()))) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }

            if (!oldUri.equals(uri)) {
                // check whether there is already another action page with this URI
                ActionPage oldPage = pageManager.findActionPageByUri(uri);
                if (oldPage != null) {
                    // action page already exists
                    ActionMessages errors = new ActionMessages();
                    errors.add("actionPageAlreadyExists", new ActionMessage("core.actionPage.errors.alreadyExists"));
                    saveErrors(request, errors);
                    saveToken(request);
                    return mapping.getInputForward();
                }
            }

            boolean uriChanged = !oldUri.equals(uri);
            if (!force && actionPage.isInUse() && uriChanged ) {
                // trying to change URI of used page - display warning
                String action = mapping.findForward("listActionPages").getPath();
                String redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
                request.getSession().setAttribute(WebappConstants.ACTION_PAGE_FORM_KEY, actionPageForm);
                ActionMessages messages = new ActionMessages();
                messages.add("changeUriWarning", new ActionMessage("core.actionPage.messages.changeUriWarning"));
                if (actionPage.doUnmodifiableLinkedObjectsExist()) {
                    messages.add("unmodifiableLinkedObjectsWarning", new ActionMessage("core.actionPage.messages.unmodifiableLinkedObjectsWarning"));
                }
                saveMessages(request, messages);

                LinkedObjectsInfoContainer container = new LinkedObjectsInfoContainer();
                container.setRedirectUrl(redirectUrl);
                container.setNewUri(uri);
                container.setUpdateAction(mapping.getPath());
                container.setObjectId(actionPage.getId());
                container.setObjectType(LinkedObjectsInfoContainer.TYPE_PAGE);
                request.getSession().setAttribute(WebappConstants.LINKED_OBJECTS_INFO_CONTAINER_KEY, container);

                return mapping.findForward("viewLinkedObjects");
            }

			WebappUtil.copyProperties(actionPage, actionPageForm, request);
            WebappUtil.fillFieldValueWithDefaultLocaleValue(actionPageForm.getTitleMap(), actionPage.getTitle(), servlet.getServletContext());
            actionPage.setTitle(actionPageForm.getTitleMap());
            WebappUtil.copyFieldValue(actionPage.getDescription(), actionPageForm.getDescriptionMap());
            WebappUtil.copyFieldValue(actionPage.getKeywords(), actionPageForm.getKeywordsMap());

            // remove links to this action page from unmodifiable menu items
            if (uriChanged) {
                for (Iterator i = actionPage.getLinkedMenuItems().iterator(); i.hasNext();) {
                    MenuItem menuItem = (MenuItem) i.next();
                    if (!menuItem.isDynamic()) {
                        i.remove();
                    }
                }
            }

            try {
                actionPage.setLastUpdatedDatetime(new Date());
                pageManager.updateActionPage(actionPage);

				//reindex action page
				SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
				searchManager.unIndexPage(oldUri, request);

				if ( actionPage.getActive().booleanValue() ) {
					searchManager.indexPage(actionPage, request);
				}

				// update cache
				CacheUtil cacheUtil = CacheUtil.getInstance(request);
				cacheUtil.flushFieldIndices();
				if ( !oldUri.equals(actionPage.getUri()) ) {

					// uri has been changed. flush all fields' cache
					cacheUtil.flushPageFieldValueCache(oldUri);
                    cacheUtil.flushPageSequenceCache(oldUri);

                    // recache all fields
					List fields = actionPage.getContentFields();
					for ( Iterator i = fields.iterator(); i.hasNext(); ) {
						ContentField field = (ContentField) i.next();
						List cfvList = field.getContentFieldValues();
						for ( Iterator j = cfvList.iterator(); j.hasNext(); ) {
							ContentFieldValue fieldValue = (ContentFieldValue) j.next();
							String content;
							if ( field.getType() == ContentField.LINE_TYPE ) {
								content = fieldValue.getSimpleValue();
							} else if ( field.getType() == ContentField.MULTILINE_TYPE ) {
								content = ConvertUtil.convertToString(fieldValue.getValue());
							} else /* if HTML_TYPE */ {
								content = ConvertUtil.convertToString(fieldValue.getValue());
							}
							CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId(), actionPageId);
							cacheUtil.putPageFieldValueInCache(cfvData, actionPage.getUri(), field.getIdentifier(), fieldValue.getContentLocale().getIdentifier());
						}
					}

                    // recache all sequences
					List sequences = actionPage.getSequences();
					for ( Iterator i = sequences.iterator(); i.hasNext(); ) {
						Sequence sequence = (Sequence) i.next();
                        CacheUtil.SequenceData sequenceData = new CacheUtil.SequenceData(sequence.getId());
                        cacheUtil.putPageSequenceInCache(sequenceData, actionPage.getUri(), sequence.getIdentifier());
					}
                } else {
					// uri has not been changed: recache internal fields only

					// title
					ContentField titleField = (ContentField) actionPage.getContentFieldsMap().get("title");
					List titleValues = titleField.getContentFieldValues();
					for ( Iterator i = titleValues.iterator(); i.hasNext(); ) {
						ContentFieldValue fieldValue = (ContentFieldValue) i.next();
						// title field is single-lined
						String content = fieldValue.getSimpleValue();
						CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, titleField.getId(), titleField.getType(), fieldValue.getId(), actionPageId);
						cacheUtil.putPageFieldValueInCache(cfvData, actionPage.getUri(), titleField.getIdentifier(), fieldValue.getContentLocale().getIdentifier());
					}

					// description
					ContentField descriptionField = (ContentField) actionPage.getContentFieldsMap().get("description");
					List descriptionValues = descriptionField.getContentFieldValues();
					for ( Iterator i = descriptionValues.iterator(); i.hasNext(); ) {
						ContentFieldValue fieldValue = (ContentFieldValue) i.next();
						// description field is single-lined
						String content = fieldValue.getSimpleValue();
						CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, descriptionField.getId(), descriptionField.getType(), fieldValue.getId(), actionPageId);
						cacheUtil.putPageFieldValueInCache(cfvData, actionPage.getUri(), descriptionField.getIdentifier(), fieldValue.getContentLocale().getIdentifier());
					}

					// keywords
					ContentField keywordsField = (ContentField) actionPage.getContentFieldsMap().get("keywords");
					List keywordsValues = keywordsField.getContentFieldValues();
					for ( Iterator i = keywordsValues.iterator(); i.hasNext(); ) {
						ContentFieldValue fieldValue = (ContentFieldValue) i.next();
						// keywords field is single-lined
						String content = fieldValue.getSimpleValue();
						CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, keywordsField.getId(), keywordsField.getType(), fieldValue.getId(), actionPageId);
						cacheUtil.putPageFieldValueInCache(cfvData, actionPage.getUri(), keywordsField.getIdentifier(), fieldValue.getContentLocale().getIdentifier());
					}

				}

                if (force) {
                    // reindex and update cache for linked objects, because they
                    // were changed

                    // flush cache related to menu items
                    cacheUtil.flushMenuCache();

                    // put linked values in cache and into search index
                    List linkedContentFieldValues = actionPage.getLinkedContentFieldValues();
                    Set owners = new HashSet();
                    for (Iterator i = linkedContentFieldValues.iterator(); i.hasNext();) {
                        ContentFieldValue fieldValue = (ContentFieldValue) i.next();
                        ContentField field = fieldValue.getContentField();
						Localizable owner = field.getOwner();
                        // put owner to set of owners to cache/reindex them later
                        owners.add(owner);

                        String localeIdentifier = fieldValue.getContentLocale().getIdentifier();

                        byte fieldType = field.getType();
                        String content;

                        if (fieldType == ContentField.LINE_TYPE) {
                            content = fieldValue.getSimpleValue();
                        } else {
                            content = ConvertUtil.convertToString(fieldValue.getValue());
                        }
                        if ( owner instanceof Page ) {
							Page page = (Page) owner;
							CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId(), owner.getId());
							cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), field.getIdentifier(), localeIdentifier);
						}
                    }

                    // process owners
                    for (Iterator i = owners.iterator(); i.hasNext();) {
                        Localizable owner = (Localizable) i.next();
						if ( owner instanceof Layout ) {
                            Layout layout = (Layout) owner;
							cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());

							//TODO: add into search index for every content page of the layout.
							//TODO: add into index action pages
							List contentPages = layout.getContentPages();
							for ( int j = 0; j < contentPages.size(); j++ ) {
								ContentPage cp = (ContentPage) contentPages.get(j);
								searchManager.reIndexPage(cp, request);
								cacheUtil.updateContentPageLastModifiedInCache(cp.getUri());
							}

						} else if ( owner instanceof Page ) {
							Page page = (Page) owner;
                            if (!actionPage.getId().equals(page.getId())) {
							    searchManager.reIndexPage(page, request);
                            }
							if ( page instanceof ContentPage ) {
								cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
							}
						}
                    }
                }

			} catch ( BeanAlreadyExistsException e ) {
				// actionPage already exists
				ActionMessages errors = new ActionMessages();
				errors.add("actionPageAlreadyExists", new ActionMessage("core.actionPage.errors.alreadyExists"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			} catch ( ObjectOptimisticLockingFailureException e ) {
				// action page was updated or deleted by another transaction
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.actionPage.errors.updateFailed"));
				saveErrors(request, errors);
				return mapping.findForward("callUpdateActionPage");
			}
			request.getSession().setAttribute(WebappConstants.ACTION_PAGE_ID_KEY, Long.valueOf(actionPageForm.getId()));
		}
		return mapping.findForward("listActionPages");
	}
}